package so.sao.code.service.domain.handler;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import so.sao.code.service.domain.entity.TagBatchConfig;
import so.sao.code.service.domain.entity.TagBatchDownloadLog;
import so.sao.code.service.domain.event.TagBatchDownloadEvent;
import so.sao.code.service.repository.TagBatchConfigDao;
import so.sao.code.service.repository.TagBatchDownloadLogDao;
import so.sao.data.dto.response.FactoryDTO;
import so.sao.data.dto.response.IndustrialComputerDTO;
import so.sao.data.feign.client.FactoryClient;
import so.sao.data.feign.client.IndustrialComputerClient;

/**
 * Created by Administrator on 2017/11/2.
 */
@Component
public class TagBatchDownloadHandler {

    @Autowired
    TagBatchDownloadLogDao tagBatchDownloadLogDao;
   @Autowired
    TagBatchConfigDao tagBatchConfigDao;
   @Autowired
   IndustrialComputerClient industrialComputerClient;
   @Autowired
   FactoryClient factoryClient;
    @EventListener
    @Async
    public void log(TagBatchDownloadEvent event) {
        TagBatchConfig tagBatchConfig=tagBatchConfigDao.findOne(event.getTagBatch().getTagBatchConfigId());
        TagBatchDownloadLog log = new TagBatchDownloadLog();
        log.setEseId(event.getUserDto().getEseId());
        log.setIp(event.getIp());
        log.setTagBatchId(event.getTagBatch().getId());
        log.setTagBatchName(event.getTagBatch().getName());
        log.setStatus(10);
        log.setMD5(event.getMD5());
        log.setOperaterName(event.getUserDto().getUsername());
        Optional<FactoryDTO> factoryDTO = Optional.ofNullable(factoryClient.findById(tagBatchConfig.getPrintFactoryId()));
        log.setPrintFactoryId(tagBatchConfig.getPrintFactoryId());
        if (factoryDTO.isPresent()) {
        	log.setPrintFactoryName(factoryDTO.get().getName());
        }
        log.setTerminalId(tagBatchConfig.getTerminalId());
        log.setSeqnumStart(event.getTagBatch().getSeqnumStart());
        log.setSeqnumEnd(event.getTagBatch().getSeqnumEnd());
        tagBatchDownloadLogDao.save(log);
    }
}
